<template>
  <div class="container">

    <div class="right-map">
      <div style="height: 100%">
        <el-amap class="amap-box" :amap-manager="amapManager" :events="events" :zoom="zoom" :vid="'amap-vue'">
          <div class="left-box">
            <a-form-model :model="carForm" v-if="!isList" :label-col="{span:5}" :wrapper-col="{span:16}" :colon="false">
              <div class="page-header">
                <span class="title-item">车辆轨迹查询</span>
              </div>
                <a-form-model-item label="车牌号" labelAlign="right">
                  <a-input placeholder="请输入车牌号" v-model="carForm.carCode"></a-input>
                </a-form-model-item>
                <a-form-model-item label="区域" labelAlign="right">
                  <a-tree-select :dropdownStyle="{maxHeight:'500px',overflow: 'auto'}" v-model="carForm.areaId" :treeData="deptList" :replaceFields="{title: 'name',key: 'id',value: 'id',children: 'menuList',}" placeholder="请选择区域"></a-tree-select>
                </a-form-model-item>
              <a-row>
                <a-col class="submit-box">
                  <a-button type="reset" class="sdefault-btn" @click="clearConditions">清空条件</a-button>
                  <a-button type="primary" @click="showCont">搜索</a-button>
                </a-col>
              </a-row>
            </a-form-model>
            <div style="height: 100%" v-if="show">
              <div class="page-header">
                <span class="title-item">车辆轨迹查询</span>
                <div class="back-btn" @click="onBack">
                  <a-icon style="color: #1890ff" type="rollback" />
                </div>
              </div>
              <div class="selectDate">
                <span style="padding: 10px">开始时间</span>
                <a-date-picker v-model="begin_time" show-time placeholder="开始时间"/>
              </div>
              <div class="selectDateEnd">
                <span style="padding: 10px">结束时间</span>
                <a-date-picker v-model="end_time" show-time placeholder="结束时间" />
              </div>
              <div class="title-box">
                <span>查询结果</span>
                <span>共{{total}}条记录</span>
              </div>
              <ul class="left-lists">
                  <li v-for="(item, index) in carList" :key="index" @click="selectFn(item)" :class="item.imei == isimei ? 'select-box' : 'wk_a'">
                    <div style="display: flex;padding: 20px 10px;border: 1px;align-items: center">
                      <div style="margin-left: 22px">
                        <img src="../../../../assets/public/car.png" alt/>
<!--                        <img v-if="item.imei == isimei" src="../../../../assets/public/车辆查询1.png" alt/>-->
<!--                        <img v-else-if="item.imei != isimei" src="../../../../assets/public/车辆查询2.png" alt/>-->
                      </div>
                      <div style="width: 100%; margin-left: 30px">
                        <span :class="item.imei == isimei ? 'wk_left' : 'wk_leftL'" style="font-size: 17px">{{ item.carCode }}</span>
                        <span style="font-size: 14px; margin: 0 5px; color: #22dc8a">{{ item.deviceInfo | filterStatus }}</span>
                      </div>
                      <div style="margin-right: 12px">
                        <a-icon title="继续" @click.stop="resumeAnimation" v-if="item.imei == isimei&&isshow==1" type="play-circle" :class="item.imei == isimei ? 'wk_left' : 'wk_leftL'" class="replayBtn"/>
                        <a-icon title="暂停" @click.stop="pauseAnimation" v-if="item.imei == isimei&&isshow==2" type="pause-circle" :class="item.imei == isimei ? 'wk_left' : 'wk_leftL'" class="replayBtn" />
                      </div>
                      <div @click.stop="historyTrack(item)">
                        <a-icon title="回放" v-if="item.imei == isimei" :class="item.imei == isimei ? 'wk_left' : 'wk_leftL'" class="replayBtn" type="redo"/>
                      </div>
                    </div>
                  </li>
              </ul>
              <div class="page-box">
                <a-pagination v-model="carForm.currentPage" :total="total" :defaultPageSize="carForm.pageSize" @change="pagechangeFn"/>
              </div>
            </div>
          </div>
        </el-amap>
      </div>

      <div v-show="isCarWindow" ref="wid" class="widow-box">
        <h3 class="h3">
          回放信息
          <a-icon
            class="guanbiicon"
            type="close-circle"
            @click="closeInfoWindow"
          />
        </h3>
        <ul>
          <li class="single">
            <p class="single-title">总里程数:</p>
            <p class="single-cent">{{ mileage.totalmilestat }}公里</p>
          </li>
          <li class="single">
            <p class="single-title">超速次数:</p>
            <p class="single-cent">{{ mileage.totaloutspeed }}次</p>
          </li>
          <li class="single">
            <p class="single-title">停留次数:</p>
            <p class="single-cent">{{ mileage.totalstop }}次</p>
          </li>
          <li class="single">
            <p class="single-title">车辆速度:</p>
            <p class="single-cent">{{ detail.speed }}km/h</p>
          </li>
          <li class="single">
            <p class="single-title">行驶方向:</p>
            <p class="single-cent">{{ detail.course | filterCourse }}</p>
          </li>
          <li class="single">
            <p class="single-title">定位时间:</p>
            <p class="single-cent">{{ gpsTime }}</p>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import "moment/locale/zh-cn";
import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
let amapManager = new AMapManager(); // 新建生成地图画布
var x_PI = (3.14159265358979324 * 3000.0) / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;
export default {
  name: "a-map",
  data() {
    let self = this;
    return {
      isshow:3,  // 播放暂停按钮的切换
      form: {
        imeis: [],
        accessToken: "",
      },
      gpsTime: moment(), //默认时间
      detail: {
        speed: "0",
      }, //窗体信息
      target: "13770618954",
      //查询的车牌号
      carForm: {
        currentPage: 1,
        pageSize: 6,
        userId: this.$user.id,
        carCode: "",
        areaId: undefined,
      },

      begin_time: moment().millisecond(0).second(0).minute(0).hour(8), //开始时间
      end_time: moment(), //结束时间
      endOpen: false,
      carList: [],
      markerArr: [], //标记的数组
      clickedMarker: "", // 已选中的点标记
      carmarker: null, //轨迹的运动图标
      deptList: [], //部门列表
      polyline: null, //行驶轨迹
      total: null,
      lineArr: [],
      linesArr: [],
      moment,
      carWindow: null, //速度框
      isCarWindow: false,
      routeInfo: null, //路线
      mileage: {}, //里程信息
      isSelect: "",
      isSelectw: "",
      isimei: "",
      isList: false,
      show: false,
      amapManager,
      mapStyle: "amap://styles/39ba2088b6b8fc67184833f73cceab4d",
      zoom: 10,
      map: "",
      events: {
        init(o) {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initPage();
          });
        },
      },
      dataList: [],
    };
  },
  //筛选方向
  filters: {
    filterCourse(value) {
      if ((value >= 0 && value <= 22.5) || (value <= 360 && value >= 337.5)) {
        return "正北方";
      }
      if (value > 22.5 && value <= 67.5) {
        return "东北方";
      }
      if (value > 67.5 && value <= 112.5) {
        return "正东方";
      }
      if (value > 112.5 && value <= 157.5) {
        return "东南方";
      }
      if (value > 157.5 && value <= 202.5) {
        return "正南方";
      }
      if (value > 202.5 && value <= 247.5) {
        return "西南方";
      }
      if (value > 247.5 && value <= 292.5) {
        return "正西方";
      }
      if (value > 292.5 && value < 337.5) {
        return "西北方";
      }
    },
    filterStatus(value) {
      if (value == 0) {
        return "在线";
      }
      if (value == 1) {
        return "未上线";
      }
      if (value == 2) {
        return "过期";
      }
      if (value == 3) {
        return "离线";
      }
      if (value == 4) {
        return "静止";
      }
    },
  },
  methods: {
    //区域监听
    selectArea(value) {
      this.carForm.areaId = value;
    },
    //清空条件
    clearConditions() {
      this.carForm = {
        currentPage: 1,
        pageSize: 6,
        userId: this.$user.id,
        carCode: "",
        areaId: undefined,
      };
    },
    //获取部门
    recursion(data) {
      data.forEach((v) => {
        // if (v.level != 3) {
        //   v.selectable = false;
        //   this.recursion(v.menuList);
        // }
      });
      return data;
    },
    getDept() {
      this.$api.AreaFindByPage(this.$user.id).then((res) => {
        if (res.data.code == 0) {
          let data = res.data.data;
          let _list = this.recursion(data);
          this.deptList = _list;
          console.log(this.deptList);
        } else {
          this.$message.info(res.data.errorMessage);
        }
        console.log(res);
      });
    },
    // getDept() {
    //   let id = 4;
    //   this.$api.getArea(id).then((res) => {
    //     this.deptList = res.data.data;
    //   });
    // },
    // 日期方法
    disabledStartDate(startValue) {
      const endValue = this.end_time;
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.begin_time;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },

    //实时获取token
    gettoken() {
      this.$api.getCarToken().then((res) => {
        this.form.accessToken = res.data.data.accessToken;
      });
    },

    //返回按钮
    onBack() {
      this.show = !this.show;
      this.isList = !this.isList;
      this.carForm.currentPage = 1;
      this.carForm.areaId = "";
      if (this.carList.length > 0) {
        this.map.remove(this.markerArr);
        this.markerArr = [];
        // this.carmarker.stopMove();
        this.map.clearMap();
        this.linesArr = [];
        this.map.remove(this.carmarker);
      }
    },
    /* 点击 */
    selectFn(item) {
      if(this.isimei == item.imei){
        return
      }
      this.linesArr=[]
      this.isshow = 3;
      this.isimei = item.imei;
      if (this.linesArr.length > 0) {
        this.carmarker.stopMove();
        this.map.clearMap();
        this.linesArr = [];
        this.map.remove(this.carmarker);
      } else {
        this.map.remove(this.markerArr);
        this.markerArr = [];
        this.markerList();
      }
      this.markerArr.forEach((item) => {
        if (item.getExtData().imei == this.isimei) {
          if (this.clickedMarker) {
            this.clickedMarker.setIcon(
              new AMap.Icon({
                image: require("@/assets/public/car.png"),
                size: new AMap.Size(52, 26), //图标大小
                imageSize: new AMap.Size(52, 26),
              })
            );
          }
          item.setIcon(
            new AMap.Icon({
              size: new AMap.Size(56, 69),
              image: require("@/assets/public/car.png"),
              imageSize: new AMap.Size(52, 26),
              imageOffset: new AMap.Pixel(0, 0),
            })
          );
          this.clickedMarker = item;
          this.map.setCenter(item.getPosition());
        }
      });
    },

    //点击搜索按钮（根据车牌号搜索）
    showCont() {
      if (this.isList == false) {
        this.show = !this.show;
        this.isList = !this.isList;
      }
      this.$api.getCarList(this.carForm).then((res) => {
        console.log(res);

        this.carList = res.data.data.records;
        this.total = res.data.data.total;
        if (this.carList.length > 0) {
          this.carList.forEach((item) => {
            this.form.imeis.push(item.imei);
          });
        } else {
          this.$message.info("未查找到数据");
        }

        this.$api.getCarLocation(this.form).then((res) => {
          this.dataList = res.data.data.data;
          this.form.imeis = [];
          this.markerList();
        });
      });
    },
    //地图初始化方法
    initPage() {
      this.map = this.amapManager.getMap();
    },
    // 分页方法
    pagechangeFn(page, pageSize) {
      this.carForm.currentPage = page;
      this.map.remove(this.markerArr);
      this.markerArr = [];
      this.showCont();
    },
    //gps转高德
    wgstogcj02(lat, lng) {
      var out = new Array();
      var gg_lat, gg_lon;
      var dlat = this.transformlat(lng - 105.0, lat - 35.0);
      var dlng = this.transformlng(lng - 105.0, lat - 35.0);
      var radlat = (lat / 180.0) * PI;
      var magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      var sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
      dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
      gg_lat = lat + dlat;
      gg_lon = lng + dlng;
      out[0] = gg_lat;
      out[1] = gg_lon;
      return out;
    },
    transformlat(lng, lat) {
      var ret =
        -100.0 +
        2.0 * lng +
        3.0 * lat +
        0.2 * lat * lat +
        0.1 * lng * lat +
        0.2 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((160.0 * Math.sin((lat / 12.0) * PI) +
          320 * Math.sin((lat * PI) / 30.0)) *
          2.0) /
        3.0;
      return ret;
    },
    transformlng(lng, lat) {
      var ret =
        300.0 +
        lng +
        2.0 * lat +
        0.1 * lng * lng +
        0.1 * lng * lat +
        0.1 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((150.0 * Math.sin((lng / 12.0) * PI) +
          300.0 * Math.sin((lng / 30.0) * PI)) *
          2.0) /
        3.0;
      return ret;
    },
    //车辆移动轨迹
    // 继续
    resumeAnimation(){
      this.carmarker.resumeMove();
      this.isshow = 2
    },
    // 暂停
    pauseAnimation() {
     this.carmarker.pauseMove();
     this.isshow = 1
    },
    // 回放
    historyTrack(item) {

      if (this.linesArr.length >= 1) {
        this.carmarker.stopMove();
        this.map.clearMap();
        this.linesArr = [];
        this.map.remove(this.carmarker);
      }

      if (this.begin_time !== "" && this.end_time !== "") {
        //点击时清除蓝色小车
        this.map.remove(this.markerArr);
        this.markerArr = [];
        //处理数据
        //处理日期
        var beginTime = JSON.parse(
          JSON.stringify(this.begin_time ? this.begin_time : "")
        );
        var endTime = JSON.parse(
          JSON.stringify(this.end_time ? this.end_time : "")
        );
        beginTime = new Date(beginTime).getTime();

        endTime = new Date(endTime).getTime();
        beginTime = parseInt(beginTime / 1000);
        endTime = parseInt(endTime / 1000);

        let imei = item.imei;
        let accessToken = this.form.accessToken;
        this.$api
          .getHistoryTrack({ beginTime, endTime, imei, accessToken })
          .then((res) => {
            this.routeInfo = res.data.data.data;
            res.data.data.data.forEach((item) => {
              let zuobiao = this.wgstogcj02(item.lat, item.lng);
              this.lineArr.push(zuobiao[1], zuobiao[0]);
              this.linesArr.push([zuobiao[1], zuobiao[0]]);
            });

            this.lineArr = [];
            this.isshow = 2;
            //设置路线
            if (this.linesArr.length == 0) {
              this.$message.info("该车辆暂未移动");
              this.isshow = 3;
              this.isCarWindow = false;
            }

            //创建小车图标
            this.carmarker = new AMap.Marker({
              map: this.map,
              position: this.linesArr[0],
              icon: "http://webapi.amap.com/images/car.png",
              offset: new AMap.Pixel(-26, -13),
              autoRotation: true,
              angle: -90,
            });

            //轨迹绘制
            this.polyline = new AMap.Polyline({
              map: this.map,
              path: this.linesArr,
              showDir: true,
              strokeColor: "#28F", //线颜色
              // strokeOpacity: 1,     //线透明度
              strokeWeight: 6, //线宽
              // strokeStyle: "solid"  //线样式
            });

            //框跟随车辆移动

            AMap.event.addListener(this.carmarker, "moving", (e) => {
              var lastLocation = e.passedPath[e.passedPath.length - 1];
              this.carWindow.setContent(
                this.setVehicleSpeedInWidowns(lastLocation)
              );

              this.carWindow.open(this.map, lastLocation);
            });

            //打开速度框
            if (this.linesArr.length > 1) {
              this.isCarWindow = true;
            }

            this.carWindow.open(this.map, this.carmarker.getPosition());

            this.map.setFitView(this.polyline);
            this.carmarker.moveAlong(this.linesArr, 200);
          });
        //获取里程信息，里程数，停留次数
        let mile = {
          accessToken: accessToken,
          imei: item.imei,
          beginTime: beginTime,
          endTime: endTime,
        };
        this.$api.getMiles(mile).then((res) => {
          this.mileage = res.data.data.summary;
          console.log(this.mileage);
        });
      } else {
        this.$message.info("请选择回放时间");
      }
    },

    // 关闭窗口方法
    closeInfoWindow() {
      this.map.clearInfoWindow();
    },

    //设置速度框
    setVehicleSpeedInWidowns(lnglat) {
      let newArr = [];
      newArr.push(this.wgstogcj02(this.routeInfo.lat, this.routeInfo.lng));
      this.linesArr.forEach((item, index) => {
        if (lnglat.lat == item.lat && lnglat.lng == item.lng) {
          this.detail = this.routeInfo[index];
          this.gpsTime = this.formatDate(this.detail.gps_time);
        }
      });
      return this.$refs.wid;
    },

    //10位时间戳转换
    formatDate(value) {
      let date = new Date(parseInt(value) * 1000);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let minute = date.getMinutes();
      let second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second;
    },

    //渲染多点
    markerList() {
      this.map.remove(this.markerArr);
      this.map.clearMap();
      this.dataList.forEach((item) => {
        let zuobiao = this.wgstogcj02(item.lat, item.lng);
        let icon = new AMap.Icon({
          size: new AMap.Size(52 * 0.7, 26 * 0.7),
          image: require("@/assets/public/car.png"),
          imageSize: new AMap.Size(52 * 0.7, 26 * 0.7),
          imageOffset: new AMap.Pixel(0, 0),
        });
        let marker = new AMap.Marker({
          position: new AMap.LngLat(zuobiao[1], zuobiao[0]),
          icon: icon,
          title: this.carList.user_name,
        });
        marker.setExtData({ imei: item.imei });
        AMap.event.addListener(marker, "click", (e) => {
          this.selectFn(item);
          this.clickedMarker = e.target;
        });
        this.markerArr.push(marker);
      });
      this.map.add(this.markerArr);
      this.map.setFitView();
    },
  },

  //把全局的背景图片取消
  mounted() {
    this.getDept();
    this.gettoken();
    //创建速度消息框
    this.carWindow = new AMap.InfoWindow({
      isCustom: true,
      offset: new AMap.Pixel(6, -25),
      content: "",
    });
    document
      .querySelector(".box-content")
      .classList.add("none-background");
  },
  beforeRouteLeave(to, from, next) {
    document
      .querySelector(".box-content")
      .classList.remove("none-background");
    next();
  },
};
</script>

<style lang="scss" scoped>
//右边整体
.container{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0;
  .left-box {
    height: 90%;
    width: 24%;
    box-sizing: border-box;
    position: absolute;
    left: 4%;
    top: 4%;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px 0 rgba(0,0,0,0.3);
    .page-header{
      font-weight: 700;
      padding: 0 14px;
      line-height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title-item{
        font-size: 18px;
        color: #000;
        width: 100%;
      }
      .back-btn {
        font-size: 20px;
        cursor: pointer;
      }
    }
    .left-lists{
      height: 70%;
      width: 100%;
      padding: 0 14px;
      overflow-y: auto;
    }
  }
  .right-map {
    height: 100%;
    width: 100%;
    position: relative;
    .amap-box {
      width: 100%;
      height: 100%;
    }
  }
}

// 信息窗体样式
.widow-box {
  width: 300px;
  height: auto;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 0 5px 0px rgb(0 0 0 / 60%);
  position: relative;
  .guanbiicon {
    font-size: 24px;
    float: right;
    // position: absolute;
    // right: 20px;
    // top: 20px;
  }
  .single {
    width: 100%;
    height: auto;
    display: flex;
    .single-title {
      width: 30%;
      // text-align: right;
    }
    .single-cent {
      width: 66%;
      color: rgb(37, 140, 215);
    }
  }
}

.submit-box {
  margin-top: 20px;
  margin-right: 40px;
  float: right;
  .sdefault-btn {
    margin: 0 20px;
  }
}
.replayBtn {
  font-size: 30px;
  cursor: pointer;
}

.selectDate {
  margin-left: 4px;
}
.selectDateEnd {
  margin-top: 10px;
  margin-left: 4px;
}
.title-box{
  width: 100%;
  margin-top: 10px;
  font-size: 14px;
  line-height: 28px;
  background: #deefff;
  padding: 0 16px;
  display: flex;
  justify-content: space-between;
}
.select-box {
  margin: 10px 0;
  background-color: #ddefff;
  border-radius: 9px;
  border: 1px solid #629cce;
  box-sizing: border-box;
}
.wk_a {
  border: 1px solid #ddf1ff;
  box-sizing: border-box;
  margin: 10px 0;
  border-radius: 9px;
  cursor: pointer;
}

.page-box {
  padding: 0 14px;
  float: right;
}
.wk_left {
  color: #629acd;
}
.wk_leftL {
  color: #629acd;
}
.wk_right {
  color: rgba(15, 208, 143);
}
.wk_rightL {
  color: rgba(38, 155, 137);
}
</style>

